# movies/admin.py

from django.contrib import admin
from .models import Movie
from django.utils.html import format_html
from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
class MovieAdmin(admin.ModelAdmin):
    # 列表页显示的字段
    list_display = ('rating', 'display_poster', 'title', 'year', 'director', 'actors', 'country', 'genre')
    # 可点击的字段（链接到修改页）
    list_display_links = ('rating', 'title')
    # 可过滤的字段
    list_filter = ('year', 'country', 'genre')
    # 可搜索的字段
    search_fields = ('title', 'director', 'quote')
    # 每页显示的数量
    list_per_page = 25
    # 默认排序
    ordering = ('rating',)
    
    # 自定义字段显示
    def display_poster(self, obj):
        if obj.poster:
            return format_html('<img src="{}" width="50" height="75" />', obj.poster)
        return "-"
    display_poster.short_description = '海报'
    
    #def douban_link(self, obj):
    #    return format_html('<a href="{}" target="_blank">豆瓣链接</a>', obj.douban_url)
    #douban_link.short_description = '豆瓣链接'
    
    # 详情页的字段分组
    fieldsets = (
        ('基本信息', {
            'fields': ('rating', 'title', 'year')
        }),
        ('创作信息', {
            'fields': ('directors', 'country', 'genre')
        }),
        ('其他信息', {
            'fields': ('quote', 'poster')
        }),
    )
    
    # 只读字段（在修改页不可编辑）
    readonly_fields = ('rating', 'title', 'year', 'director', 'actors', 'country', 'genre', 'quote')

# 注册模型和自定义的ModelAdmin
admin.site.register(Movie, MovieAdmin)
